package com.exp.bookhouse.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.exp.bookhouse.pojo.Role;
import com.exp.bookhouse.pojo.myUser;
import com.exp.bookhouse.pojo.vo.UserDetailVo;
import com.exp.bookhouse.service.RoleService;
import com.exp.bookhouse.service.UserService;
import com.exp.bookhouse.util.Base64DecodeMultipartFile;
import io.swagger.annotations.*;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authc.IncorrectCredentialsException;
//import org.apache.shiro.authc.LockedAccountException;
//import org.apache.shiro.authc.UnknownAccountException;
//import org.apache.shiro.authc.UsernamePasswordToken;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
//import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.Subject;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "用户管理接口",tags = "管理员管理用户操作")
@Controller
@RequestMapping("/admin")
public class UserControllerAdmin {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "分页查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "p", value = "页数", required = false, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "s", value = "显示记录数", required = false, dataType = "Int"),
    })
//    @RequiresPermissions({"select"})
    @GetMapping("/toUser")
    public String toUser(@RequestParam(value = "p",required = false,defaultValue = "1")Integer page,
                         @RequestParam(value = "s",required = false,defaultValue ="5")Integer size,
                         Model model){
        IPage<myUser> iPage = userService.queryUserByPage(page,size);
        model.addAttribute("iPage",iPage);
        return "user";
    }


    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @GetMapping("/toSaveUser")
    public String toSaveUser(){
        return "userAdd";
    }



    @ApiOperation(value = "查询用户可以添加的角色")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true, dataType = "Long")
    })
//    @RequiresPermissions({"select"})
    @GetMapping("/toUserAddRole/{id}")
    public String toUserAddRole(@PathVariable("id")Long userId, Model model){
        List<Role> roles = userService.queryOtherRoles(userId);
        model.addAttribute("userId",userId);
        model.addAttribute("roles",roles);
        return "userAddRole";
    }



    @ApiOperation(value = "添加用户角色")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "userId", value = "用户id", required = true, dataType = "Long"),
            @ApiImplicitParam(paramType = "form", name = "ids", value = "用户id", required = true, allowMultiple = true, dataType = "String")
    })
//    @RequiresPermissions({"add"})
    @PostMapping("/saveUserAddRole")
    public String saveUserAddRole(@RequestParam("userId")Long userId, @RequestParam("ids")String[] roleIds){
        userService.saveUserAddRole(userId,roleIds);
        return "redirect:/admin/toUser";
    }

    @ApiOperation(value = "查询用户角色详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "编号", required = true,dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "p", value = "页码", required = true,dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "s", value = "页数", required = true,dataType = "Int")
    })
//    @RequiresPermissions({"select"})
    @GetMapping("/queryUserDetail/{id}/{p}/{s}")
    public String queryUserDetail(@PathVariable("id")Long id, @PathVariable("p")Integer page, @PathVariable("s")Integer size, Model model){
        IPage<Role> iPage = roleService.queryRolesByUserIdAndPage(id,page,size);
        myUser myUser = userService.queryUserById(id);
        UserDetailVo userDetailVo = new UserDetailVo();
        userDetailVo.setMyUser(myUser);
        userDetailVo.setiPage(iPage);
        model.addAttribute("userDetailVo",userDetailVo);
        return "userDetail";
    }


    @ApiOperation(value = "添加用户")
//    @RequiresPermissions({"add"})
    @PostMapping("/saveUser")
    public String saveUser(@ApiParam(value = "用户信息",required = true) myUser myUser, @ApiParam(value = "上传的文件", required = true) @RequestParam("file") MultipartFile file) throws Exception {
        userService.saveUser(myUser, file);
        return "redirect:/admin/toUser";
    }


    @ApiOperation(value = "查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true, dataType = "Long")
    })
//    @RequiresPermissions({"select"})
    @GetMapping("/toUpdateUser/{id}")
    public String toUpdateUser(@PathVariable("id")Long id, Model model){
        myUser myUser = userService.queryUserById(id);
        model.addAttribute("user", myUser);
        return "userUpdate";
    }


    @ApiOperation(value = "更新用户")
//    @RequiresPermissions({"update"})
    @PostMapping("/updateUser")
    public String updateUser(@ApiParam(value = "用户信息",required = true) myUser myUser, @ApiParam(value = "用户头像文件",required = true) @RequestParam("file") MultipartFile file) throws IOException {
        userService.updateUser(myUser,file);
        return "redirect:/admin/toUser";
    }

    @ApiOperation(value = "删除用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true, dataType = "Long")
    })
//    @RequiresPermissions({"delete"})
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id")Long id){
        userService.deleteUser(id);
        return "redirect:/admin/toUser";
    }


//    @RequiresPermissions({"select"})
    @GetMapping("/toProfile")
    public String toProfile(HttpSession session, Model model){
        myUser loginMyUser = (myUser) session.getAttribute("user");
        myUser myUser = userService.queryUserById(loginMyUser.getId());
        myUser.setPassword(null);
        model.addAttribute("user", myUser);
        return "profile";
    }

    @ApiOperation(value = "更新用户头像")
//    @RequiresPermissions({"update"})
    @PostMapping("/changeAvatar")
    public @ResponseBody
    Map<String,Object> changeAvatar(@ApiParam(value = "头像url",required = true) @RequestBody String avatar, HttpSession session, Model model) throws Exception {
        myUser myUser = (myUser) session.getAttribute("user");
        String decode = URLDecoder.decode(avatar);
        MultipartFile file = Base64DecodeMultipartFile.base64Convert(decode);
        String url = userService.changeAvatar(file, myUser.getId());
        myUser.setHeadImage(url);
        session.setAttribute("user", myUser);
        model.addAttribute("user", myUser);
        HashMap<String, Object> map = new HashMap<>();
        map.put("url",url);
        return map;
    }


//    @PostMapping("/login")
//    @ApiOperation(value = "登录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true,dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true,dataType = "String")
//    })
//    public String login(@RequestParam("username")String username, @RequestParam("password")String password,
//                        @RequestParam(value = "rememberMe",required = false, defaultValue = "false")Boolean rememberMe,
//                        Model model){
//        //1.获取当前用户对象
//        Subject currentUser = SecurityUtils.getSubject();
//        //2.封装当前用户和密码为token
//        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//
//        try{
//            //3.执行登录操作
//            token.setRememberMe(rememberMe);
//            currentUser.login(token);  //如果没有异常说明登录成功
//
//            return "redirect:/admin/toIndex";		//登录成功，跳转首页
//        }catch (UnknownAccountException e){
//            model.addAttribute("msg","用户名错误");
////            model.addAttribute("msg","用户名或密码错误");
//            return "login";		//登录失败，跳转登录页
//        }catch (IncorrectCredentialsException e){
//            model.addAttribute("msg","密码错误");
////            model.addAttribute("msg","用户名或密码错误");
//            return "login";		//登录失败，跳转登录页
//        }catch (LockedAccountException e){
//            model.addAttribute("msg","用户名："+token.getPrincipal()+"被锁定，请联系管理员解锁");
//            return "login";		//登录失败，跳转登录页
//        }
//    }

    @RequestMapping("/login")
    public String login() {
        //这里什么都不错，由Spring Security负责登录验证
        return "/login";
    }



    /**
     * 退出
     * @param
     * @return
     */
//    @GetMapping("/logout")
//    public String logout(){
//        Subject subject = SecurityUtils.getSubject();
//        if (subject.isAuthenticated()) {
//            subject.logout(); // session 会销毁，在sessionlistener监听session销毁，清理权限缓存
//        }
//        return "login";
//    }
}
